package com.ww.springboot.boot.controller;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.NumberUtil;
import com.ww.springboot.boot.bus.IDataMachiningService;
import com.ww.springboot.boot.exception.BusinessException;
import com.ww.springboot.boot.exception.MyExceptionInterceptor;
import com.ww.springboot.boot.model.ExportMessageDto;
import com.ww.springboot.boot.util.CalculatorUtil;
import com.ww.springboot.boot.util.HexUtil;
import com.ww.springboot.boot.util.SudokuUtil;
import com.ww.springboot.boot.util.SudokuUtil2;
import com.ww.springboot.boot.utils.Func;
import com.ww.springboot.boot.utils.JacksonUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author wanwei
 * 数据加工
 * @date: 2019年2月18日 下午3:42:51
 */

@RequestMapping("/dataMachining")
@AllArgsConstructor
@Controller
public class DataMachiningController {


    private final IDataMachiningService dataMachiningService;

    /**
     * 初始页面
     *
     * @return
     */
    @RequestMapping("")
    public String list() {
        return "dataMachining/list";
    }


    /**
     * 初始页面
     *
     * @return
     */
    @RequestMapping("/regular")
    @ResponseBody
    public String regular(String type, String regular, String content, Boolean isAdd
            , Boolean isMulti, Boolean isRemoveMulti, Boolean isIgnoreZCase, Boolean isGroup) {
        int flag = 0x00;
        if (isMulti) {
            flag |= Pattern.MULTILINE;
        }
        if (isIgnoreZCase) {
            flag |= Pattern.CASE_INSENSITIVE;
        }
        Pattern r;
        if (flag == 0x00) {
            r = Pattern.compile(regular);
        } else {
            r = Pattern.compile(regular, flag);
        }
        Boolean groupFlag = isGroup;

        List<String> list = new ArrayList<>();
        Matcher m = r.matcher(content);
        while (m.find()) {
            if (StringUtils.isEmpty(m.group())) {
                continue;
            }
            if (m.groupCount() != 0 && groupFlag) {
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i <= m.groupCount(); i++) {
                    sb.append(m.group(i)).append(",");
                }
                list.add(sb.substring(0, sb.length() - 1));
                continue;
            }
            list.add(m.group());
        }

        list = removeMulti(isRemoveMulti, list);

        switch (type) {
            case "1":
                content = list.stream().collect(Collectors.joining("\n"));
                break;
            case "2":
                content = list.stream().collect(Collectors.joining(","));
                break;
            case "3":
                content = "\"" + list.stream().collect(Collectors.joining("\",\"")) + "\"";
                break;
            default:
        }
        if (isAdd) {
            content = "(" + content + ")";
        }
        return content;
    }

    /**
     * 初始页面
     *
     * @return
     */
    @RequestMapping("/concat")
    @ResponseBody
    public String concat(String concat, String content) {
        List<String> list = Func.toStrList("\n", content);
        StringBuilder stringBuilder = new StringBuilder();
        list.forEach(str->{
            stringBuilder.append(String.format(concat,str.split(","))).append(";\n");
        });
        return stringBuilder.toString();
    }

    /**
     * 初始页面
     *
     * @return
     */
    @RequestMapping("/simple")
    @ResponseBody
    public String simple(String type, String content, Boolean isAdd, Boolean isRemoveMulti) {
        content = content.replace("\r", "");
        content = content.replace(" ", "");
        content = content.replace("\n", ",");

        List<String> list = Arrays.stream(content.split(",")).collect(Collectors.toList());

        list = removeMulti(isRemoveMulti, list);

        switch (type) {
            case "1":
                content = list.stream().collect(Collectors.joining(","));
                break;
            case "2":
                content = "\"" + list.stream().collect(Collectors.joining("\",\"")) + "\"";
                break;
            default:
        }
        if (isAdd) {
            content = "(" + content + ")";
        }
        return content;
    }

    /**
     * 初始页面
     *
     * @return
     */
    @RequestMapping("/removeDup")
    @ResponseBody
    public String removeDup(String content, String contentDup, Boolean isRemoveMulti) {
        System.out.println(content);
        System.out.println(contentDup);
        content = content.replace("\r", "");
        content = content.replace(" ", "");
        content = content.replace("\n", ",");

        List<String> list = Arrays.stream(content.split(",")).collect(Collectors.toList());

        contentDup = contentDup.replace("\r", "");
        contentDup = contentDup.replace(" ", "");
        contentDup = contentDup.replace("\n", ",");

        List<String> listDup = Arrays.stream(contentDup.split(",")).collect(Collectors.toList());
        list.removeAll(listDup);

        list = removeMulti(isRemoveMulti, list);

        String result = list.stream().collect(Collectors.joining(","));

        return result;
    }

    private List<String> removeMulti(Boolean isRemoveMulti, List<String> list) {
        if (isRemoveMulti) {
            list = list.stream().distinct().collect(Collectors.toList());
        }
        return list;
    }


    /**
     * 数独
     *
     * @return
     */
    @RequestMapping("/sudoku")
    @ResponseBody
    public String sudoku(String content) {
        String[] array = content.split("\n");
        int[][] arrays = new int[9][9];
        for (int i = 0; i < array.length; i++) {
            String ss = array[i];
            for (int j = 0; j < ss.length(); j++) {
                arrays[i][j] = Integer.valueOf(String.valueOf(ss.charAt(j)));
            }
        }
        SudokuUtil2.solve(arrays);
        return SudokuUtil.print(arrays);
    }

    /**
     * 计算器
     *
     * @return
     */
    @RequestMapping("/calculator")
    @ResponseBody
    public String calculator(String content) {
        content = content.replace("\n", "");
        content = content.replace("\r", "");
        content = content.replace(" ", "");
        content = content.replace("=", "");
        String suffix = CalculatorUtil.changeToSuffix(content);

        Double result = CalculatorUtil.count(suffix);

        String resultStr = "" + result;
        if (result % 1 == 0) {
            resultStr = "" + result.longValue();
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("后缀表达式:").append(suffix).append(";\n").append("结果:").append(resultStr);

        if (suffix.contains("&")
                || suffix.contains("^")
                || suffix.contains("|")) {
            String[] array = suffix.split(",");
            stringBuilder.append("\n\n二进制:\n");
            for (int i = 0; i < array.length; i++) {
                if (NumberUtil.isInteger(array[i])) {
                    stringBuilder.append(supple(HexUtil.hexChange(Long.valueOf(array[i]), 2), 32)).append(":")
                            .append(array[i]).append("\n");
                }
            }
            stringBuilder.append(supple(HexUtil.hexChange(result.longValue(), 2), 32)).append(":")
                    .append(result.longValue()).append("\n");
        }
        return stringBuilder.toString();
    }

    private String supple(String str, Integer index) {
        String space = "";
        for (int i = 0; i < index - str.length(); i++) {
            space += "  ";
        }
        return space + str;
    }

    /**
     * 进制
     *
     * @return
     */
    @RequestMapping("/hex")
    @ResponseBody
    public String hex(String content, String hex) {
        content = content.replace("\n", "");
        content = content.replace("\r", "");
        content = content.replace(" ", "");
        return HexUtil.hexChange(Long.valueOf(content), Integer.valueOf(hex));
    }


    /**
     * 识图
     *
     * @date :2017年9月8日
     * @return:String
     */
    @RequestMapping(value = "/readFile", method = RequestMethod.POST)
    @ResponseBody
    public String readFile(@RequestParam MultipartFile multipartFile,@RequestParam String type) {
        return dataMachiningService.readFile(multipartFile,type);
    }



}
